package com.example.firstapp.network

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.firstapp.R
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class CallbacktestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_callbacktest)
        httpURLConnection()
    }
    // 调用httpURLConnection进行网络请求
    // 并且在参数中实现化接口中的onFinish和onError方法，最后回调这个接口的方法
    fun httpURLConnection(){
        HttpUtil.sendHttpRequest("address", object : HttpCallbackListener {
            override fun onFinish(response: String) {
                // 得到服务器返回的具体内容
            }
            override fun onError(e: Exception) {
                // 在这里对异常情况进行处理
            }
        })
    }
    fun okhttp(){
        val client = OkHttpClient()
        val request = Request.Builder()
            .url("address")
            .build()
        // 自动切换到后台线程
        client.newCall(request).enqueue(object:Callback{
            override fun onFailure(call: Call, e: IOException) { //切换到主线程
                TODO("Not yet implemented")
            }

            override fun onResponse(call: Call, response: Response) {
                TODO("Not yet implemented")
            }
        })
    }
}